<?php

namespace App\Http\Controllers;

use App\Service\BMR\BMR_Metabolize;
use App\Service\BMR\Metabolize\BasialMetabolize;
use App\Service\BMR\Metabolize\Man;
use App\Service\BMR\Metabolize\Woman;
use App\Service\BMR\Nutrition\Carbohydrate;
use App\Service\BMR\Nutrition\Fat;
use App\Service\BMR\Nutrition\Protein;
use App\Service\UserBuilderService;
use App\Service\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MbrDateController extends Controller
{
    //评测表单页
    public function index($date = '', UserBuilderService $userBuilderService) {
        $date = empty($date) ? date('Y-m-d') : $date;
        //评测
        $builder = $this->bmrUser->lastBuilder()->first();
        if (!$builder) return redirect('/calculate/count');
        //评测的食物配置
        $foods   = $userBuilderService->getFoodsHot($builder, $date);
        //评测的总营养
        $totalHot= $userBuilderService->getBuilderMbr($builder);
        $data = [
            'user' => $this->bmrUser,
            'info' => $builder,
            'foods'=> $foods,
            'date' => $date,
            'rest' => [
                'protein'   => $totalHot['protein'] - collect($foods)->sum(function($food){ return $food->food_protein; }),
                'fat'       => $totalHot['fat'] - collect($foods)->sum(function($food){ return $food->food_fat; }),
                'carbohydrate'=> $totalHot['carbohydrate'] - collect($foods)->sum(function($food){ return $food->food_carbohydrate; }),
            ]
        ];
        return view('bmr/date', $data);
    }

    //评测
    public function update(Request $request, UserService $userService, UserBuilderService $userBuilderService) {
        if ($request->isMethod('post')) {
            $inputs = $request->all();

            DB::transaction(function() use ($userService, $userBuilderService, $inputs) {
                //统计食物营养以及热量
                $inputs = array_merge($inputs, $userBuilderService->getMbr($inputs));
                //更新用户性别
                $userService->updateSex($this->bmrUser, $inputs['sex']);
                //更新热量数据
                $userBuilderService->updateOrCreate($this->bmrUser, $inputs);
            });
            $data = [];
            return redirect('/calculate/count');
        }
    }
}